//-------------导入mysql包-----------------
const mysql = require('mysql');

//------------创建数据库连接-----------------
const con = mysql.createConnection({
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: '1234',
  database: 'todolist',
});

//-------------------连接---------------------
con.connect();

//-------------------操作---------------------

//获取所有数据
function getAll(sql) {
  return new Promise((resolve, reject) => {
    con.query(sql, function (err, data) {
      if (err) reject(err);
      resolve(data);
    });
  });
}

//根据id获取
function getById(sql) {
  return new Promise((resolve, reject) => {
    con.query(sql, function (err, data) {
      if (err) reject(err);
      data[0] ? resolve(data[0]) : resolve(null);
    });
  });
}

//写入操作(增.删.改)
function exec(sql) {
  return new Promise((resolve, reject) => {
    con.query(sql, function (err, data) {
      if (err) reject(err);
      resolve(data);
    });
  });
}

//----------------------导出对象-----------------
module.exports = {
  getAll,
  getById,
  exec,
};
